#include <mymuduo/TcpServer.h>
#include <mymuduo/Logger.h>

#include <string>
#include <functional>
#include <unistd.h>

class EchoServer
{
public:
    EchoServer(EventLoop *loop,
               const InetAddress& listenAddr/*监听的ipPort*/,
               const std::string& name/*服务器名称*/)
               : server_(loop, listenAddr, name)
               , loop_(loop)
    {
        // 注册回调函数
        server_.setConnectionCallback(
            std::bind(&EchoServer::onConnection, this, std::placeholders::_1)
        );

        server_.setMessageCallback(
            std::bind(&EchoServer::onMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)
        );

        // 设置合适的subloop线程数量
        server_.setThreadNum(3);
    }

    void start()
    {
        server_.start();
    }

private:
    EventLoop* loop_;
    TcpServer server_;

    // 连接建立或者断开的回调
    void onConnection(const TcpConnectionPtr& conn)
    {
        if(conn->connected())
        {
            // 连接成功，打印对端ipPort
            LOG_INFO("connection UP : %s\n", conn->peerAddress().toIpPort().c_str());
        }
        else
        {
            LOG_INFO("connection DOWN : %s\n", conn->peerAddress().toIpPort().c_str());
        }
    }
    
    // 可读写事件回调
    void onMessage(const TcpConnectionPtr& conn,
                   Buffer* buf,
                   Timestamp time)
    {
        std::string msg = buf->retrieveAllAsString();  // 获取缓冲区的数据
        conn->send(msg);  // 发送给客户端
        conn->shutdown();  // 关闭写端  底层发生EPOLLHUP事件 -> closeCallback_
    }
};

int main()
{
    EventLoop loop;
    InetAddress addr(8000);

    EchoServer server(&loop, addr, "EchoServer-01");  // 创建了一个Acceptor → create、bind 一个 non-blocking listenfd
    server.start();  // listen  创建subLoop listenfd打包成acceptchannel，并注册到mainloop → 接收新连接
    loop.loop();  // 启动mainloop的底层Poller

    return 0;
}